<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>基于Vue购物车</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>

<body>
<div class="container">
    <div id="app">
        <div v-if="books.length">
            <table class="table table-bordered">
                <thead>
                <tr>
                    <th></th>
                    <th>书籍名称</th>
                    <th>出版日期</th>
                    <th>价格</th>
                    <th>数量</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item,index) in books">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.data}}</td>
                    <td>{{item.price|filter}}</td>
                    <td>
                        <button class="btn btn-default" type="button" @click="sub(index)" :disabled="item.count == 1">
                            -
                        </button>
                        {{item.count}}
                        <button class="btn btn-default" type="button" @click="add(index)">+</button>
                    </td>
                    <td>
                        <button class="btn btn-default" type="button" @click="remove(index)">移除</button>
                    </td>
                </tr>
                </tbody>
            </table>
            总价：{{sum|filter}} 元
        </div>
        <div v-else>购物车空了哎</div>
    </div>
</div>
<script src="../js/vue.js"></script>
<script>
  new Vue({
    el: '#app',
    data: {
      books: [
        {id: 1, name: '书籍1', data: '2019-9-1', price: 60, count: 3},
        {id: 2, name: '书籍2', data: '2019-9-1', price: 70, count: 6},
        {id: 3, name: '书籍3', data: '2019-9-1', price: 50, count: 13},
        {id: 4, name: '书籍4', data: '2019-9-1', price: 30, count: 33}
      ],
      allprice: 0,
      emptyStatus: true
    },
    methods: {
      add(index) {
        ++this.books[index].count
      },
      sub(index) {
        --this.books[index].count;
      },
      remove(index) {
        this.books.splice(index, 1);
      }
    },
    computed: {
      sum() {
        return this.books.reduce((total, item) => {
          return total + item.price * item.count;
        }, 0)
      }
    },
    //过滤器
    filters: {
      filter(price) {
        return '￥' + price.toFixed(2)
      }
    }
  })
</script>

</body>
</html>